# This very makefile (main.mk) is the most recently loaded makefile (lastword MAKEFILE_LIST).
# We use this information as the base directory for further include directives below.
DIR_MAKEFILET := $(dir $(lastword $(MAKEFILE_LIST)))include

RM ?= $(shell which rm) -f
BUILD_ID = $(shell which git >/dev/null && git log -1 --pretty=format:%h || echo "unknown")

DIR_BUILD ?= build
DIR_DIST ?= dist
# e.g. for "debian/rules install"
DESTDIR ?= root


include $(DIR_MAKEFILET)/generic.mk
include $(DIR_MAKEFILET)/release.mk
# 'deb-common' is used for simple deb packages and for pypi2deb packages
include $(DIR_MAKEFILET)/deb-common.mk

# TODO: remove this global flag and move it to individual (failing) projects
DISABLE_SHELL_CHECK ?= 1
ifeq ($(DISABLE_SHELL_CHECK),)
	include $(DIR_MAKEFILET)/shell.mk
endif

# Debian packaging
DIR_DEBIAN_BUILD ?= $(DIR_BUILD)/debian
ifneq ($(wildcard debian/changelog),)
	include $(DIR_MAKEFILET)/deb.mk
endif

# pypi2deb packaging
DIR_PYPI2DEB_BUILD ?= $(DIR_BUILD)/pypi2deb
PYPI2DEB_PACKAGES ?=
ifneq ($(PYPI2DEB_PACKAGES),)
	include $(DIR_MAKEFILET)/pypi2deb.mk
endif

# pypi/python packaging
# DIR_PYTHON_SETUP can be overwritten by the project
DIR_PYTHON_SETUP ?= .
PYTHON_SETUP_FILE = $(DIR_PYTHON_SETUP)/setup.py
ifneq ($(wildcard $(PYTHON_SETUP_FILE)),)
	include $(DIR_MAKEFILET)/python.mk
	# by default a project-related virtual environment is used
	DISABLE_CUSTOM_VIRTUALENV ?=
	ifneq ($(DISABLE_CUSTOM_VIRTUALENV),1)
		VIRTUALENV_REQUIREMENTS_FILE ?= requirements.txt
		ifneq ($(wildcard $(VIRTUALENV_REQUIREMENTS_FILE)),)
			include $(DIR_MAKEFILET)/python-virtualenv.mk
		endif
	endif
	ifneq ($(wildcard manage.py),)
		include $(DIR_MAKEFILET)/python-django.mk
	endif
	# set the test arguments if they were not overridden by another component (e.g. Django)
	PYTHON_TEST_ARGS ?= -m unittest discover
endif


.PHONY: help
help: help-makefilet

.PHONY: help-makefilet
help-makefilet:
	@echo "Common makefilet targets:"
	@echo "    dist"
	@echo "    help"
	@echo "    install"
	@echo "    report"
	@echo "    test"
	@echo "    upload"
	@echo

.PHONY: clean
clean: clean-makefilet

.PHONY: clean-makefilet
clean-makefilet:
	$(RM) -r "$(DIR_BUILD)"
	# remove installation root directory (only if it is a subdirectory of the project)
	if echo "$(abspath $(DESTDIR))" | grep -q "^$(shell pwd)"; then $(RM) -r "$(DESTDIR)"; fi
	@# A changed DIR_BUILD could cause the makefilet download directory to survive the above
	@# clean operation. We detect the "automatic download" situation based on a non-empty
	@# DIR_MAKEFILET_DOWNLOAD variable.
	if [ -n "$(DIR_MAKEFILET_DOWNLOAD)" ]; then $(RM) -r "$(DIR_MAKEFILET_DOWNLOAD)"; fi

.PHONY: dist-clean
dist-clean: clean
	$(RM) -r "$(DIR_DIST)"


# Reset the default goal. The next processed target (usually in the Makefile of the project) will
# be the default target.
.DEFAULT_GOAL :=
